package com.tutu.user.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import com.tutu.common.GlobalConstants;
import com.tutu.user.entity.SysMenuInfo;
import com.tutu.user.service.ISysMenuInfoService;
import com.tutu.user.service.ISysUserService;

/**
 * 根据URL获取所需权限
 * @author tutu
 *	@date 2013-11-19
 *	@company cjcc
 *	@version ssi_1.0 1.0
 */
@Service("mySecurityMetadataSource")
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource{

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ISysMenuInfoService sysMenuInfoService;
	
	private final Map<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
	
//	public MySecurityMetadataSource(){
//		try {
//			this.loadRequestMap();
//		} catch (Exception e) {
//			this.log.error("加载所有权限失败", e);
//		}
//	}
	
	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		HttpServletRequest request = ((FilterInvocation)object).getRequest();
		for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap.entrySet()) {
            if (entry.getKey().matches(request)) {
                return entry.getValue();
            }
		}
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return Boolean.TRUE;
	}
	
	/**
	 * 初始所有权限
	 * @throws Exception
	 */
	@PostConstruct
	private void loadRequestMap() throws Exception{
//		String superUser = ResourceBundle.getBundle("common").getString("SUPER_USER");
		SysMenuInfo sysMenuInfo = new SysMenuInfo();
		sysMenuInfo.setAliveFlag(GlobalConstants.FLAG_ENABLE);
		Set<SysMenuInfo> sysMenuInfos = new HashSet<SysMenuInfo>(this.sysMenuInfoService.getSysMenuInfos(sysMenuInfo));
		for(Iterator<SysMenuInfo> sysMenuInfoIterator = sysMenuInfos.iterator(); sysMenuInfoIterator.hasNext(); ){
			sysMenuInfo = sysMenuInfoIterator.next();
			if(StringUtils.isEmpty(sysMenuInfo.getMenuUrl()))
				continue;
			if(!StringUtils.startsWith(sysMenuInfo.getMenuUrl(), "/")){
				sysMenuInfo.setMenuUrl("/"+sysMenuInfo.getMenuUrl());
			}
			String outprint = sysMenuInfo.getMenuUrl().replace("?", "\\?") + "*";
//			outprint = outprint.replace(".", "\\.");
			this.logger.debug("URL路径["+outprint+"]权限加载");
//			RequestMatcher requestMatcher = new RegexRequestMatcher(outprint, null);
			RequestMatcher requestMatcher = new AntPathRequestMatcher(outprint, null);
			if(requestMap.containsKey(requestMatcher))
			{
				ConfigAttribute configAttribute = new SecurityConfig(sysMenuInfo.getMenuCode());
				Collection<ConfigAttribute> collect = requestMap.get(requestMatcher);
				collect.add(configAttribute);
			}
			else
			{
				Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
				if(StringUtils.isEmpty(sysMenuInfo.getMenuCode())){
					this.logger.error("权限主ID有空");
					continue;
				}
				ConfigAttribute configAttribute = new SecurityConfig(sysMenuInfo.getMenuCode());
				configAttributes.add(configAttribute);
				requestMap.put(requestMatcher, configAttributes);
			}
		}
//		全部路径权限默认赋于ROLE_ALL
//		RequestMatcher requestMatcher = new AntPathRequestMatcher("/**");
//		Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
//		ConfigAttribute configAttribute = new SecurityConfig("ROLE_ALL");
//		configAttributes.add(configAttribute);
//		requestMap.put(requestMatcher, configAttributes);
	}
	
}
